var eventObj = require("./app/mock/event");
define(function(require , exports , module){
	angular.module("App" , ["dialogs"])
	.factory("App" , function($rootScope , $http , $location , $dialogs , $timeout){
 
    function App() {
      this.$http = $http;
      this.$location = $location;
      this.statusCodes = {ok:200,created:201 , error:500, notfound:404 , timeout:301};
      this.loaded = false;
      this.listeners = new Map();
      this.timer;
      this.intervals = new Array();
      this.resizeFun;
    };

    /** load app resource */
    App.prototype.init = function() {
      var $this = this;
      this.loadConstants();
      this.loadResources();
      //绑定视图刷新事件 去除自定义事件
      $rootScope.$on("$routeChangeStart" , function(){
        $this.clearListener();
        $this.clearIntervals();
        $this.clearWindowResize();
      })

    };
    
    App.prototype.hasUserPermission = function(crud){
    	  var user = $rootScope.authUser ;
          if(this.isSuperAdmin()){
        	  return true; 
          }else{
        	  var roles = user.roles;
              for(var i = 0 ; i < roles.length;i++){
            	 var roleCode = roles[i];
            	 if(roleCode.indexOf("_")!=-1 && roleCode.split("_")[1] == crud ) {
            		 return true;
            	 }
              }
         	  return false;
          }
    }
    App.prototype.isSuperAdmin = function(){
    	  var user = $rootScope.authUser ;
    	  if(user.id==1){
        	  return true; 
          }else{
        	  return false;
          }
    }
    App.prototype.loadConstants = function() {

    };
	
	App.prototype.loadResources = function() {
     var $this = this;
     $http({
        method:"GET",  
        url: "./datas/BasicData.json"
        }).success(function(data){
          angular.extend($this , data);
        }).error(function(data,status){
          console.log('error');
        })
	};

	App.prototype.initConnect = function() { 
	var $this = this;
	
	};
	
	App.prototype.sendCommand = function(command , data) {
		var command = {command: command, data:data};
	};
  	
	App.prototype.closeConnect = function() {

  };
  	
	App.prototype.resetConnect = function() {

	};

  App.prototype.addListener = function(event , func) {
    if (!this.listeners.containsKey(event)) {
        this.listeners.put(event , new Array());
    }
      this.listeners.get(event).push(func);
    $rootScope.$on(event , func);
  };

  App.prototype.removeListener = function(event , func) {
       if (!this.listeners.containsKey(event)) {
          return;
      }
      var funcs = this.listeners.get(event);

      var namedListeners = $rootScope.$$listeners[event];
      for (var j = 0,len = funcs.length;j < len;j++) {
          var eventFun = funcs[j];
          if (func === undefined || eventFun === func)
          {
              if (namedListeners) {
                  for (var i = 0, len = namedListeners.length;i < len;i++) {
                      if (namedListeners[i] === eventFun) {
                          namedListeners.splice(i , 1);
                      }
                  }
              }
              funcs.splice(j , 1);
          }

      }
      if (funcs.length === 0) {
          this.listeners.remove(event);
      }
  };

    App.prototype.clearListener = function() {
      var keys = this.listeners.keys();
      for (var i = 0,len = keys.length;i < len;i++) {
        var key = keys[i];
        this.removeListener(key);

      }
    };
    
    App.prototype.addInterval = function(fun , time) {
    	this.intervals.push(window.setInterval(fun , time));
    }
    
    App.prototype.clearIntervals = function() {
        for (var i = 0, len = this.intervals.length;i < len;i++) {   
        	window.clearInterval(this.intervals[i]);
        	this.intervals.splice(i , 1);            
        }
	  } 
    App.prototype.addWindowResize = function(fun){
    	this.resizeFun = fun ;
    	window.addEventListener("resize" ,fun , false) ; 
    	
    }
    App.prototype.clearWindowResize = function(){
    	window.removeEventListener("resize",this.resizeFun,false);
    }

    App.prototype.changeModalWidth = function(width){
	    $timeout(function(){
	    	$(".modal-dialog").css("width" , width + "px"); 
	    },
	    500);
    };
  	

    var app =  new App();
    app.init();
 	  app.initConnect();
    $rootScope.App = app;
	
    return app;
  })
  .filter("codeName" , ["$rootScope" , "App" , function($rootScope , App){
    return function(text) {
      if (text == null || text === 'undefined') {
    	 return "";
      }
      var code =  _.findWhere($rootScope.codes,{"codeValue":text});
      return code ==null ? text : code.codeName;

    }
  }])
  .filter("str" , function(){
    return function(data) {
      return data === undefined?"":data.toString();
    }
  })
  .filter("parentCode" , ["$rootScope" , "App" , function($rootScope , App){
    return function(datas , parentCode) {
        var parentId;
        var code =  _.findWhere(datas,{"code":parentCode});
        if(code!=null){
            parentId = code.id;
        }
        if (parentId) {
           return  _.where(datas,{"parentId":parentId});
        }
        else {
           return [];
        }
    }
  }])
  .filter("sysCode" , ["$rootScope" , "App" , function($rootScope , App){
    return function(text , parentCode) {
        if (!text) {
            return null;
        }
        var parentId;
        var parent=  _.findWhere($rootScope.codes,{"code":parentCode});
        if(parent!=null){
            parentId = parent.id;
        }
       if (parentId) {
        var code =  _.findWhere($rootScope.codes,{"parentId":parentId,"codeValue":text});
          if(code!=null){
              return code.codeName;
          }
      }
      return null;
    }
  }])
  .filter("lineName" , ["$rootScope" , "App" , function($rootScope , App){
    return function(text) {
        if (!text) {
    	    return "";
        }
        var line =  _.findWhere($rootScope.lines,{"id":text});
        return line == null ? text : line.name;
     }
  }])
  .filter("lineNameByCode" , ["$rootScope" , "App" , function($rootScope , App){
    return function(text) {
        if (!text) {
    	    return "";
        }
        var line =  _.findWhere($rootScope.lines,{"code":text});
        return line == null ? text : line.name;
    }
  }])
   .filter("sectionCode" , ["$rootScope" , "App" , function($rootScope , App){
    return function(text) {
      if (!text) {
    	  return "";
      }
      var section =  _.findWhere($rootScope.sections,{"id":text});
      return section == null ? text : section.code;
    }
  }])
  .filter("sectionDesc",["$rootScope" , "$filter",function($rootScope , $filter){
	  return function(text){		  
	      if (!text) {
	    	  return "";
	      }
	      var section = null;
          var section =  _.findWhere($rootScope.sections,{"code":text});
	      if(!section){
	    	  return "";
	      }	      
	      var fromStationCode = section.fromStation;
	      var toStationCode = section.toStation;
	      return $filter("stationName")(fromStationCode) + "-" + $filter("stationName")(toStationCode); 
	  }  
  }])
   .filter("orgName" , ["$rootScope" , "App" , function($rootScope , App){
    return function(text) {
      if (!text) {
    	  return "";
      }
      var org =  _.findWhere($rootScope.orgs,{"id":text});
      return org == null ? text : org.name;
    }
  }])
 .filter("field" , ["$rootScope" , "App" , function($rootScope , App){
    return function(text , field) {
		var datas = $rootScope.constants[field];
        var data = _.findWhere(datas , {"value":text});
        return data==null ? field : data.text;
    }
  }])
  .filter("toLowerCase" , ["$rootScope" , "App" , function($rootScope , App){
    return function(text) {		
		return text.substring(0,1).toLowerCase() + text.substring(1,text.length);	  	
    }
  }])
  .filter("notIn" , [function(){
	return function(text , list) {
		console.log(text);
		console.log(list);
	}
  }]);
});